package com.cytech.cloudclinic.dialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cytech.cloudclinic.R;
import com.cytech.cloudclinic.adapter.AddDrugTagAdapter;
import com.cytech.cloudclinic.adapter.AddTemplateAdapter;
import com.cytech.cloudclinic.base.BaseBean;
import com.cytech.cloudclinic.base.BaseObserver;
import com.cytech.cloudclinic.bean.AddDrugTag;
import com.cytech.cloudclinic.bean.Drug;
import com.cytech.cloudclinic.bean.PrescriptionTag;
import com.cytech.cloudclinic.bean.event.RefreshAction;
import com.cytech.cloudclinic.bean.event.RefreshCategory;
import com.cytech.cloudclinic.bean.event.UpdateAddTagEvent;
import com.cytech.cloudclinic.moudle.main.setting.prescription.drugs.PrescriptionDrugActivity;
import com.cytech.cloudclinic.utils.ConvertUtils;
import com.cytech.cloudclinic.utils.RequestWithViewUtils;
import com.yechaoa.yutils.ToastUtil;
import com.yechaoa.yutils.YUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.cytech.cloudclinic.app.Constant.MODE_BODY_POINT_ID;

/**
 * 新增处方模板
 */
public class AddPrescriptionTemplateDialog extends DialogFragment {
    @BindView(R.id.et_add_prescription_template_name)
    EditText categoryName;
    @BindView(R.id.rv_add_prescription_template)
    RecyclerView categoryRv;

    private List<PrescriptionTag> mList;
    private AddTemplateAdapter addTemplateAdapter;

    private int drugParentTagId;


    public AddPrescriptionTemplateDialog(int drug_tag_id) {
        Bundle bundle = new Bundle();
        bundle.putInt("drug_tag_id",drug_tag_id);
        setArguments(bundle);
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.width = (int) (0.9* YUtils.getScreenWidth());
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        getDialog().getWindow().setAttributes(lp);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_add_prescription_template, null);
        ButterKnife.bind(this, view);
        builder.setView(view);
        EventBus.getDefault().register(this);

        drugParentTagId = getArguments().getInt("drug_tag_id");

        mList = new ArrayList<>();
        addTemplateAdapter = new AddTemplateAdapter(mList);
        addTemplateAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                addTemplateAdapter.setCurrentPos(position);
            }
        });
        categoryRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        categoryRv.setAdapter(addTemplateAdapter);
        getPrescriptionTags(drugParentTagId);

        return builder.create();
    }



    @OnClick(R.id.dialog_update_unit_cancel)
    public void onClickCancel(View view){
        dismiss();
    }

    @OnClick(R.id.dialog_update_unit_save)
    public void onClickSave(View view){
        if(TextUtils.isEmpty(categoryName.getText().toString())){
            ToastUtil.showToast("请填写处方名称");
            return;
        }
        PrescriptionDrugActivity.actionStart(getActivity(),drugParentTagId,addTemplateAdapter.getCurrentSelectId(),categoryName.getText().toString());
        dismiss();
    }

    @OnClick(R.id.btn_add_template_category)
    public void addCategory(View view){
        AddTemplateGroupDialog dialog = new AddTemplateGroupDialog(drugParentTagId);
        dialog.show(getChildFragmentManager(),"tag_category");
    }


    //获取处方列表
    public void getPrescriptionTags(int drugParentTag) {
        JSONObject json = new JSONObject();
        try {
            json.put("drug_tag",drugParentTag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String requestStr = json.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestStr);
        RequestWithViewUtils.getInstance().addDisposable(RequestWithViewUtils.getInstance().apiServer.getPrescriptionTags(body), new BaseObserver<BaseBean<List<PrescriptionTag>>>(null, true) {

            @Override
            public void onSuccess(BaseBean<List<PrescriptionTag>> o) {
               addTemplateAdapter.setNewInstance(o.result);
            }

            @Override
            public void onError(String msg) {
                ToastUtil.showToast(msg);
            }
        });
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateData(RefreshCategory event) {
        getPrescriptionTags(drugParentTagId);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
